package com.jltx.xq.coroutinesandrxpro.ext

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

inline fun <T> LifecycleOwner.observeLaunchIn(
    source: Flow<T>,
    crossinline action: (T) -> Unit
) {
    source.onEach { action.invoke(it) }
        .launchIn(lifecycleScope)
}


inline fun <T> LifecycleOwner.observeWithLifecycle(
    source: Flow<T>,
    crossinline action: (T) -> Unit
) {
    source.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
        .onEach { action.invoke(it) }
        .launchIn(lifecycleScope)
}